import { isReferee } from "@/func";
import { GameComponent, RegionTeamChooser } from "@sapi-game/gameComponent";
import { Game } from "@sapi-game/main";
import { DimensionIds } from "@sapi-game/utils/vanila-data";
import { BlockedLobbyState } from "../states/lobbyState";
import { Duration, Logger } from "@sapi-game/utils";
import { mapObject } from "@sapi-game/utils/func";
import { PlayerInteractWithBlockBeforeEvent, system } from "@minecraft/server";
import { BlockedInCombat } from "../game";

export class BlockedInCombatStarter extends GameComponent<BlockedLobbyState> {
    private isCountingDown = false;
    private logger = new Logger(this.constructor.name);

    override onAttach(): void {
        //开始木牌
        this.subscribe(Game.events.signClick, (t) => this.handleStart(t), {
            dimensionId: DimensionIds.Overworld,
            loc: { x: 872, y: -51, z: 945 },
            clickInterval: 5,
        });
        this.subscribe(
            Game.events.interval,
            () => {
                const teams = this.state.teams;
                const cnt = mapObject(teams, (t) => t.validSize);
                this.state.lobbyRegion.forEachPlayer((p) => {
                    p.onScreenDisplay.setActionBar(
                        `§c红队:${cnt.red} §b蓝队:${cnt.blue} §a绿队:${cnt.green} §e黄队:${cnt.yellow}`
                    );
                });
            },
            new Duration(5)
        );
    }

    handleStart(t: PlayerInteractWithBlockBeforeEvent) {
        if (this.isCountingDown) {
            return t.player.sendMessage("不要重复开始");
        }
        if (!isReferee(t.player)) {
            t.player.sendMessage("你不是管理员，无权操作");
            return;
        }
        if (!this.state.canStartGameByPlayerCount()) {
            t.player.sendMessage("人数不足，无法开始");
            return;
        }
        if (Game.manager.hasGame(BlockedInCombat)) {
            return t.player.sendMessage("游戏已开始");
        }
        system.run(() => {
            this.startCountDown();
        });
    }

    startCountDown() {
        this.state.deleteComponent(RegionTeamChooser);
        this.isCountingDown = true;
        this.runner.run(async (r) => {
            try {
                for (let i = 5; i > 0; i--) {
                    this.state.groupSet.title(i.toString());
                    this.state.groupSet.forEach((p) =>
                        p.player.playSound("random.click")
                    );
                    await r.wait(20);
                }
                this.state.start();
            } catch (err) {
                this.logger.error("开始游戏失败", err);
            } finally {
                this.isCountingDown = false;
            }
        });
    }
}
